package com.longteng.diamond.interceptor;

import com.longteng.diamond.constant.ConstantType;
import com.longteng.diamond.domain.Project;
import com.longteng.diamond.domain.User;
import com.longteng.diamond.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator
 * DATE : 2018/5/20
 * TIME : 16:25
 * PROJECT : java-lesson
 * PACKAGE : com.longteng.lesson
 *
 * @author <a href="mailto:taki@qq.com">Administrator</a>
 */

public class MyInterceptor implements HandlerInterceptor {
    private UserService userService;


    /**
     *
     * @param userService
     * @return
     * @description 传入userService进来
     */
    public MyInterceptor(UserService userService){
        this.userService =userService;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("user");
        if (null == user) {
            /**因为是ajax，是无法重定向的**/
            if(ConstantType.XMLHTTPREQUEST.equals(request.getHeader(ConstantType.XREQUESTEDWith))){
                /**告诉ajax我是重定向**/
                response.setHeader("REDIRECT", "REDIRECT");
                /**告诉ajax我重定向的路径**/
                response.setHeader("CONTENTPATH", "/loginController/loginPage");
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            }else{
                response.sendRedirect("/loginController/loginPage");
            }
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println(">>>MyInterceptor>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println(">>>MyInterceptor2>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
    }
}
